package org.swfer.UIC 
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	/**
	 * 拖动条
	 * 必须部件 up,bar
	 * 回调事件 draging,drag_start,drag_complete
	 * @author swfer
	 */
	public class Slider extends Component 
	{
		//回掉事件类型
		public static const DRAGING:String = 'draging';
		public static const DRAG_START:String = 'drag_start';
		public static const DRAG_COMPLETE:String = 'drag_complete';
		
		protected var _value:Number = 0;
		protected var bar:Sprite;
		protected var up:DisplayObject;
		protected var width:int;
		protected var height:int;
		
		public function Slider(view:MovieClip) 
		{
			super(view);
		}
		
		///////////////////////////////////
		// methods
		///////////////////////////////////
		
		override public function dispose():void
		{
			if (disposed) return;
			super.dispose();
			
			bar = null;
			up = null;
		}
		
		override protected function init():void
		{
			width = view.width;
			height = view.height;
			
			up = view['up'] as DisplayObject;
			bar = view['bar'] as Sprite;
			
			up.x = -width;
		}
		
		override protected function addEvt():void
		{
			bar.addEventListener(MouseEvent.MOUSE_DOWN,startDrag);
		}
		
		override protected function removeEvt():void
		{
			bar.removeEventListener(MouseEvent.MOUSE_DOWN, startDrag);
			
			view.stage.removeEventListener(MouseEvent.MOUSE_MOVE,onDraging);
			view.stage.removeEventListener(MouseEvent.MOUSE_UP, release);
		}
		
		///////////////////////////////////
		// evt handlers
		///////////////////////////////////
		
		private function startDrag(e:MouseEvent):void 
		{
			bar.startDrag(false,new Rectangle(0, bar.y, width-bar.width, 0));
			view.stage.addEventListener(MouseEvent.MOUSE_MOVE,onDraging);
			view.stage.addEventListener(MouseEvent.MOUSE_UP, release);
			executeCallBack(DRAG_START);
		}
		
		private function release(e:MouseEvent):void 
		{
			view.stage.removeEventListener(MouseEvent.MOUSE_MOVE,onDraging);
			view.stage.removeEventListener(MouseEvent.MOUSE_UP, release);
			bar.stopDrag();
			executeCallBack(DRAG_COMPLETE);
		}
		
		private function onDraging(e:MouseEvent):void 
		{
			executeCallBack(DRAGING);
			_value = bar.x / (width - bar.width);
			up.x = -width * (1 - _value);
		}
		
		///////////////////////////////////
		// getters/setters
		///////////////////////////////////
		
		/** [0~1]浮点数 **/
		public function get value():Number { return _value;}
		public function set value(value:Number):void 
		{
			_value = value;
		}
		
	}

}